package com.dkd.manage.aspect;


import com.dkd.common.core.domain.model.LoginUser;
import com.dkd.manage.annotation.AutoFill;
import com.dkd.manage.constant.AutoFillConstant;
import com.dkd.manage.constant.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.dkd.manage.mapper.*.*(..)) && @annotation(com.dkd.manage.annotation.AutoFill)")
    public void pointCut() {}

    @Before("pointCut()")
    public void AutoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("为公共字段自动赋值");
        //获取方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法的AutoFill注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType type = autoFill.value();

        //定义要赋值的对象
        LocalDateTime now = LocalDateTime.now();
        // 获取当前登录用户信息
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String user = loginUser.getUsername();

        //获取要操作的对象
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0) {
            return;
        }
        Object obj = args[0];

        //判断操作类型
        if(type.equals(OperationType.INSERT)) {
            //利用反射实现字段的赋值
            Method setCreateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateBy = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_BY, String.class);
            Method setUpdateBy = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_BY, String.class);

            setCreateTime.invoke(obj, now);
            setUpdateTime.invoke(obj, now);
            setCreateBy.invoke(obj, user);
            setUpdateBy.invoke(obj, user);
        }else {
            Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateBy = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_BY, String.class);

            setUpdateTime.invoke(obj, now);
            setUpdateBy.invoke(obj, user);
        }
    }

}
